package com.tledu.spring.controller;

import com.tledu.spring.core.constants.CommonConstants;
import com.tledu.spring.core.entity.AjaxResult;
import com.tledu.spring.core.exception.LoginException;
import com.tledu.spring.domain.Cus;
import com.tledu.spring.service.ICusService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @author Lsj
 * @version 1.0
 * @date 2021/7/5 11:09
 */
@Controller
@AllArgsConstructor
public class LoginController {
    private final ICusService cusService;

    @GetMapping("/login")
    public String login() {
        return "login";
    }

    @PostMapping("/login")
    @ResponseBody
    public AjaxResult<Cus> login(String c_name, String c_password, HttpSession session) {
        Cus cus = cusService.login(c_name, c_password);
        session.setAttribute(CommonConstants.LOGIN_USER_SESSION_KEY, cus);
        return new AjaxResult<Cus>(cus);
    }
    @ResponseBody
    @ExceptionHandler({LoginException.class})
    public AjaxResult<String> handleCustomException(LoginException e){
        System.out.println("e.getMessage:"+e.getMessage());
        return new AjaxResult<>(e.getMessage());
    }

    /**
     * 主页面
     *
     * @return 地址
     */
    @RequestMapping("/index")
    public String index(Model model, HttpServletRequest request) {
        System.out.println("进入到index中");
        Cus cus = (Cus) request.getSession().getAttribute(CommonConstants.LOGIN_USER_SESSION_KEY);
        model.addAttribute("name",cus.getC_name());
        return "index";
    }
}
